<?php
namespace api\modules\v1\models;

use api\common\models\User;
use Yii;
use yii\base\Model;
use yii\web\HttpException;
/**
 * Login form
 */
class Login extends Model
{
    public $username;
    public $password;

    private $_user;

    public $type='';
    public $openid='';

    public $nickname;
    public $head_img;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'password'], 'required', 'on' => ['login']],

            ['username','validateUsername', 'on' => ['login']],

            ['password', 'validatePassword', 'on' => ['login']],

            ['type', 'required','message'=>'第三方登录方式不能为空', 'on' => ['third']],

            ['openid', 'required','message'=>'第三方登录ID不能为空', 'on' => ['third']],

            ['type', 'in', 'range' => ['qq','wx','wb'], 'on' => ['third']],

            //昵称 头像
            ['nickname', 'validateNickName', 'on' => ['third']],
            ['head_img', 'url', 'on' => ['third']],
        ];
    }


    public function attributeLabels()
    {
        return [
            'username' => Yii::t('app', '账号'),
            'password' => Yii::t('app', '密码'),
        ];
    }

    public function validateNickName($attribute, $params){
        if(isset($this->nickname)){
            $this->nickname = strip_tags($this->nickname);
        }
        return true;
    }

    public function validateUsername()
    {
        if (!$this->hasErrors()) {
            $users = $this->getUser();
            if(empty($users)){
                $this->addError('username', '用户未注册');
                return false;
            }
        }
        return true;

    }
    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
            if($user->password_hash == ''){
                $this->addError($attribute, '您还未设置密码,请使用短信登录或者第三方登录!');
                return false;
            }
            if (!$user || !$user->validatePassword($this->password)) {
                $this->addError($attribute, '账号或密码错误!');
                return false;
            }
        }
        return true;
    }

    /**
     * Logs in a user using the provided username and password.
     *
     * @return boolean whether the user is logged in successfully
     */
    public function login()
    {
        if ($this->validate()) {
            $user = User::findByUsername($this->username);
            return Yii::$app->user->login($this->getUser());
        } else {
            return false;
        }
    }

    public function loginThird()
    {
        if ($this->validate()) {
            $openid_field = $this->type.'_openid';
            if(!$user = User::findOne(["$openid_field"=>$this->openid,'status'=>10])){
                throw new HttpException(444,'尚未注册',0);
                //$this->addError($this->type, $this->type.'第三方登录失败');
                return false;
            }

            $update_data =[];
            if(isset($this->nickname) && $this->nickname != '' && $user['nickname'] ==''){
                $update_data['nickname'] = $this->nickname;
                $user['nickname'] = $this->nickname;
            }
            if(isset($this->head_img) && $this->head_img != '' && $user['head_img'] ==''){
                $update_data['head_img'] = $this->head_img;
                $user['head_img'] = $this->head_img;
            }
            if(count($update_data) >0 ){
                User::updateAll($update_data,['id'=>$user['id']]);
            }

            return $user;
        } else {
            return false;
        }
    }

    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    protected function getUser()
    {
        if ($this->_user === null) {
            $this->_user = User::findByUsername($this->username);
        }

        return $this->_user;
    }
}
